package com.yunban;

import cn.hutool.json.JSONUtil;
import net.lab1024.sa.base.common.annoation.NoNeedLogin;
import net.lab1024.sa.base.listener.Ip2RegionListener;
import net.lab1024.sa.base.listener.LogVariableListener;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author lijiajun
 */
@RestController
@EnableCaching
@EnableAsync
@EnableScheduling
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@MapperScan(basePackages = {ApplicationStarterApplication.COMPONENT_SCAN, ApplicationStarterApplication.YUNBAN_COMPONENT_SCAN}, annotationClass = Mapper.class)
@SpringBootApplication(exclude = {UserDetailsServiceAutoConfiguration.class})
@ComponentScan(basePackages = {ApplicationStarterApplication.COMPONENT_SCAN, ApplicationStarterApplication.YUNBAN_COMPONENT_SCAN})
public class ApplicationStarterApplication {

    public static final String COMPONENT_SCAN = "net.lab1024.sa";
    public static final String YUNBAN_COMPONENT_SCAN = "com.yunban";

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(ApplicationStarterApplication.class);
        // 添加 日志监听器，使 log4j2-spring.xml 可以间接读取到配置文件的属性
        application.addListeners(new LogVariableListener(), new Ip2RegionListener());

        application.run(args);
    }

    @NoNeedLogin
    @GetMapping(value = "/typewriter", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter typewriter() {
        // 设置较长的超时时间或使用默认值
        SseEmitter emitter = new SseEmitter();

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("msg", "第" + i + "行");
                    // 使用 SseEmitter.event() 方法发送数据
                    emitter.send(SseEmitter.event().data(map).name("message")  // 可选：指定事件名称
                            .id(String.valueOf(i))  // 可选：指定事件ID
                    );
                    TimeUnit.SECONDS.sleep(1);
                }
                emitter.complete();
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            } finally {
                executorService.shutdown();
            }
        });

        return emitter;
    }
}
